<template>
  <el-dialog
    :title="rowData.id ? $t('common.edit') : $t('common.add')"
    :visible.sync="dialogVisible"
    :show="show"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    append-to-body
    :before-close="handleClose"
    width="800px"
    @open="open"
    destroy-on-close
  >
    <el-form
      ref="form"
      v-loading="infoLoading"
      :model="info"
      :rules="rules"
      label-width="140px"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item :label="$t('buyer.informationType')" prop="type">
            <el-select v-model="info.type">
              <el-option
                v-for="item in typeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            v-if="parseInt(info.type) === 2"
            :label="$t('buyer.provinceAndCity')"
            prop="address"
          >
            <el-cascader
              v-model="info.address"
              :options="cityMapOptions"
              :props="{ value: 'label' }"
            ></el-cascader>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item :label="$t('buyer.demandTitle')" prop="title">
            <el-input
              type="textarea"
              v-model="info.title"
              :placeholder="$t('buyer.demandTitle')"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item :label="$t('buyer.productImage')" prop="image">
            <el-upload
              list-type="picture-card"
              :action="uploadAction"
              :on-change="imgPreview"
              accept=".jpeg,.png,.jpg"
              :limit="6"
              :on-exceed="handleExceed"
              :on-preview="handlePictureCardPreview"
              :on-remove="handleRemove"
              :on-success="onSuccess"
              :file-list="fileList"
            >
              <i class="el-icon-plus"></i>
              <template #tip>
                <div class="el-upload__tip">
                  提示：只允许上传.jpg,.jpeg,.png格式图片, 且大小不超过2M,
                  最多支持上传6张
                </div>
              </template>
            </el-upload>
            <el-dialog
              :title="$t('common.preview')"
              :visible.sync="dialogVisible_pic"
              :close-on-click-modal="false"
              :close-on-press-escape="false"
              append-to-body
            >
              <img width="100%" :src="dialogImageUrl" alt="" />
            </el-dialog>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item :label="$t('buyer.demandDetails')" prop="details">
            <el-input
              type="textarea"
              :autosize="{ minRows: 4 }"
              v-model="info.details"
              class="w-full"
              :placeholder="$t('buyer.demandDetails')"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="parseInt(info.type) === 1">
        <el-col :span="12">
          <el-form-item :label="$t('common.nation')" prop="country">
            <el-input v-model="info.country" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('buyer.countryFlag')" prop="countryFlag">
            <el-input v-model="info.countryFlag" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item :label="$t('buyer.demand')" prop="requireQuantity">
            <el-input type="text" v-model="info.requireQuantity" />
          </el-form-item>
        </el-col>
        <el-col :span="12" v-if="parseInt(info.type) === 1">
          <el-form-item :label="$t('buyer.targetPrice')" prop="targetPrice">
            <el-input
              type="text"
              v-model="info.targetPrice"
              :placeholder="$t('buyer.targetPrice')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12" v-if="parseInt(info.type) === 2">
          <el-form-item :label="$t('buyer.demandAmount')" prop="requireAmount">
            <el-input
              type="text"
              v-model="info.requireAmount"
              :placeholder="$t('buyer.demandAmount')"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row v-if="parseInt(info.type) === 1">
        <el-col :span="24">
          <el-form-item :label="$t('buyer.purchaseTag')" prop="categoryStub">
            <el-input
              type="text"
              v-model="info.categoryStub"
              placeholder="当有多个采购标签时,请用“|”进行分隔"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="parseInt(info.type) === 1">
        <el-col :span="12">
          <el-form-item :label="$t('buyer.destination')" prop="destination">
            <el-input type="text" v-model="info.destination" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('buyer.supplierArea')" prop="supplierArea">
            <el-input type="text" v-model="info.supplierArea" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="parseInt(info.type) === 1">
        <el-col :span="12">
          <el-form-item :label="$t('buyer.payment')" prop="paymentTerms">
            <el-input type="text" v-model="info.paymentTerms" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            :label="$t('buyer.shippingMethod')"
            prop="shippingTerms"
          >
            <el-input type="text" v-model="info.shippingTerms" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="parseInt(info.type) === 2">
        <el-col :span="12">
          <el-form-item :label="$t('dataSearch.contactPerson')" prop="contacts">
            <el-input type="text" v-model="info.contacts" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('common.email')" prop="mailbox">
            <el-input type="text" v-model="info.mailbox" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="parseInt(info.type) === 2">
        <el-col :span="12">
          <el-form-item :label="$t('buyer.wechat')" prop="wechat">
            <el-input type="text" v-model="info.wechat" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('buyer.phone')" prop="phone">
            <el-input type="text" v-model="info.phone" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item :label="$t('buyer.releaseTime')" prop="releaseTime">
            <el-date-picker
              value-format="yyyy-MM-dd"
              v-model="info.releaseTime"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('buyer.expireTime')" prop="expireTime">
            <el-date-picker
              value-format="yyyy-MM-dd"
              v-model="info.expireTime"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item :label="$t('common.remark')" prop="remark">
            <el-input
              type="textarea"
              :autosize="{ minRows: 3 }"
              v-model="info.remark"
              class="w-full"
              :placeholder="$t('common.remark')"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <div slot="footer" class="dialog-footer">
      <el-row>
        <el-col :span="12" class="btnEdit">
          <el-button :disabled="infoLoading" type="primary" @click="subInfo">{{
            $t('permission.confirm')
          }}</el-button>
        </el-col>
        <el-col :span="12" class="btnEdit">
          <el-button @click="handleClose">{{ $t('common.cancel') }}</el-button>
        </el-col>
      </el-row>
    </div>
  </el-dialog>
</template>

<script>
import { postAction } from '@/api/common'
import cityMap from './chinaMap.json'

export default {
  name: 'edit',
  props: {
    show: {
      type: Boolean,
      default: false,
    },
    rowData: {
      type: Object,
      // 对象或数组默认值必须从一个工厂函数获取
      default: function () {
        return false
      },
    },
  },
  data() {
    return {
      fileList: [],
      dialogImageUrl: '',
      dialogVisible_pic: false,
      uploadAction: '/api/Upload/UploadBuyerDataImg',
      dialogVisible: this.show,
      isChange: false,
      initForm: true,
      cityMapOptions: cityMap,
      typeOptions: [
        {
          value: 1,
          label: this.$t('buyer.globalSupplier'),
        },
        {
          value: 2,
          label: this.$t('buyer.internalSupplier'),
        },
      ],
      // 页面元素
      info: {
        files: '',
        image: [],
      },
      infoLoading: true,
      // 验证
      rules: {
        title: [
          {
            required: true,
            message: this.$t('common.enter', [this.$t('buyer.demandTitle')]),
            trigger: 'change',
          },
        ],
        details: [
          {
            required: true,
            message: this.$t('common.enter', [this.$t('buyer.details')]),
            trigger: 'change',
          },
        ],
        country: [
          {
            required: true,
            message: this.$t('common.enter', [this.$t('common.nation')]),
            trigger: 'change',
          },
        ],
        targetPrice: [
          {
            required: true,
            message: this.$t('common.enter', [this.$t('buyer.targetPrice')]),
            trigger: 'change',
          },
        ],
        destination: [
          {
            required: true,
            message: this.$t('common.enter', [this.$t('buyer.destination')]),
            trigger: 'change',
          },
        ],
        supplierArea: [
          {
            required: true,
            message: this.$t('common.enter', [this.$t('buyer.supplierArea')]),
            trigger: 'change',
          },
        ],
        paymentTerms: [
          {
            required: true,
            message: this.$t('common.enter', [this.$t('buyer.payment')]),
            trigger: 'change',
          },
        ],
        shippingTerms: [
          {
            required: true,
            message: this.$t('common.enter', [this.$t('buyer.shippingMethod')]),
            trigger: 'change',
          },
        ],
        releaseTime: [
          {
            required: true,
            message: this.$t('common.enter', [this.$t('buyer.releaseTime')]),
            trigger: 'change',
          },
        ],
        expireTime: [
          {
            required: true,
            message: this.$t('common.enter', [this.$t('buyer.expireTime')]),
            trigger: 'change',
          },
        ],
        address: [
          {
            required: true,
            message: this.$t('common.enter', [
              this.$t('buyer.provinceAndCity'),
            ]),
            trigger: 'change',
          },
        ],
      },
    }
  },

  watch: {
    show() {
      this.dialogVisible = this.show
      this.initForm = true
    },
    info: {
      handler: function () {
        if (this.initForm) {
          this.isChange = false
          this.initForm = false
        } else {
          this.isChange = true
        }
      },
      deep: true,
    },
  },
  methods: {
    async open() {
      this.infoLoading = true
      // eslint-disable-next-line eqeqeq
      if (this.rowData.id) {
        this.info = this.rowData
        if (this.rowData.address) {
          this.info.address = this.rowData.address.split('-')
        }
        console.log('this.rowData.image:' + this.rowData.image)
        this.fileList = this.rowData.image
      } else {
        this.fileList = []
        this.info = {
          type: 1,
        }
      }
      this.infoLoading = false
    },
    // 添加图片
    imgPreview(file, fileList) {
      this.infoLoading = true
      const isType =
        file.raw.type === 'image/jpeg' ||
        file.raw.type === 'image/jpg' ||
        file.raw.type === 'image/png'
      const isLt2M = file.raw.size / 1024 / 1024 < 2
      if (!isType) {
        // 移除最后一个元素
        fileList.pop()
        this.$message.error('上传图片只能是 JPG,JPEG,PNG 格式!')
        this.infoLoading = false
      }
      if (!isLt2M) {
        // 移除最后一个元素
        fileList.pop()
        this.$message.error('上传图片大小不能超过 2MB!')
        this.infoLoading = false
      }
      this.infoLoading = false
    },

    // 上传图片
    onSuccess(res, file, fileList) {
      console.table(res)
      console.table(file)
      console.table(fileList)

      // 这里是element的上传地址，对应的name,url,自己打印fileList对照
      this.fileList.push({ name: file.name, url: res.data })
      console.table(this.info.image)
    },
    handleRemove(file, fileList) {
      console.log(file.uid)
      let Pics = this.info.image
      Pics.forEach((item, index) => {
        if (file.uid == item.uid) {
          Pics.splice(index, 1)
        }
      })
    },
    // 提交表单
    subInfo() {
      this.$refs.form.validate(async (valid) => {
        // form验证
        if (valid) {
          let res
          console.log('this.fileList:' + this.fileList)
          console.log('tt:' + JSON.stringify(this.fileList))
          this.info.image = JSON.stringify(this.fileList)
          if (this.info.type === 2) {
            this.info.address =
              this.info.address[0] + '-' + this.info.address[1]
          }
          if (this.info.id) {
            res = await postAction(this.info, 'buyerData/Edit')
          } else {
            res = await postAction(this.info, 'buyerData/Add')
          }
          //this.$message.success('提交成功')
          if (res.code === 20000) {
            this.$message({
              type: 'success',
              message: res.message,
              center: true,
            })
          } else {
            this.$message({
              type: 'warning',
              message: res.message,
              center: true,
            })
          }
          this.infoLoading = false
          // 调用父级页面方法
          this.closeAction()
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 图片预览
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible_pic = true
    },
    // 上传图片个数限制
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 6 个文件，本次选择了 ${files.length} 个文件，共选择了 ${
          files.length + fileList.length
        } 个文件`
      )
    },
    handleClose(done) {
      if (this.isChange) {
        this.$confirm(
          this.$t('common.unsavedChangesTip'),
          this.$t('common.tips'),
          {
            type: 'warning',
          }
        )
          .then((_) => {
            this.$emit('update:show', false)
            this.reset()
          })
          .catch((_) => {})
      } else {
        this.reset()
        this.$emit('update:show', false)
      }
    },
    closeAction() {
      this.$emit('closeAction')
    },
    reset() {
      this.info = {}
    },
  },
}
</script>

<style scoped></style>
